package com.codeoss.framework.view.service.impl;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.codeoss.framework.context.YunContext;
import com.codeoss.framework.converter.IConverter;
import com.codeoss.framework.converter.IConverterStore;
import com.codeoss.framework.data.metadata.Column;
import com.codeoss.framework.data.metadata.Table;
import com.codeoss.framework.data.store.ITableStore;
import com.codeoss.framework.expression.Expression;
import com.codeoss.framework.util.DictDef;
import com.codeoss.framework.util.LookupInfo;
import com.codeoss.framework.util.StringUtils;
import com.codeoss.framework.view.component.Component;
import com.codeoss.framework.view.component.Page;
import com.codeoss.framework.view.component.Select;
import com.codeoss.framework.view.datasource.DataSourceConfig;
import com.codeoss.framework.view.service.ISelectComponentService;
import com.codeoss.framework.view.service.IVariableService;

@Service
public class SelectComponentService extends ComponentService implements ISelectComponentService {
	@Autowired
	private ITableStore tableStore;
	@Autowired
    private IVariableService variableService;
	@Autowired
	private IConverterStore converterStore;
	
	@Override
	public void processValue(YunContext yunContext, Component component,Map<String,String> paraMap,Map<String,Object> dataMap) {
		// TODO Auto-generated method stub
		Select select=(Select)component;
		if(paraMap.containsKey(select.getId())) {
			String value=paraMap.get(select.getId());
			Page page=yunContext.getPage();
			DataSourceConfig dataSourceConfig=page.getDataSourceConfigById(select.getDataSource());
			Table table=tableStore.get(dataSourceConfig.getTableName());
			Column column=table.getColumnByColumnName(select.getDataField());
			LookupInfo lookupInfo=column.getLookupInfo();
			if(lookupInfo!=null) {
				DictDef dictDef=lookupInfo.getDictDef();
				if(dictDef!=null) {
					variableService.setVariableValue(yunContext, select.getVarName(), value);
				}else {
					if(!StringUtils.isEmpty(value)) {
						IConverter converter=converterStore.getConverter(column.getDataType());
						variableService.setVariableValue(yunContext, select.getVarName(), converter.convertStringToObject(value));
					}else {
						variableService.setVariableValue(yunContext, select.getVarName(), null);
					}
				}
			}
		}
	}
	
	@Override
	public void processEvent(YunContext yunContext, Component component, String eventType) {
		super.processEvent(yunContext, component, eventType);
		Select select=(Select)component;
		if ("changeEvent".equals(eventType)) {
			Expression onChangeExpression = select.getOnChangeExpression();
			if (onChangeExpression != null) {
				executeEventExpression(yunContext, component, onChangeExpression,null);
			}
		}
	}
}
